<?php

namespace App\Imports;

use App\Http\Common\BaseController;
use App\Models\UserRole;
use App\Models\Company\CompanyUserModel;
use App\Models\Grade;
use App\Models\Role;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;

class CompanyUserImport extends BaseController implements ToCollection
{
    /**
     * 使用 ToCollection
     * @param array $row
     *
     * @return User|null
     */
    public function collection(Collection $rows)
    {
        try {
            $rows = json_decode($rows, true);

            for($i = 1;$i<count($rows);$i++){
                if(empty($rows[$i][0])){
                    continue;
                }
                $username = $rows[$i][0];
                $grade = $rows[$i][2];
                $role= $rows[$i][1];
                $phone = $rows[$i][3];

                if (User::where('phone' ,'=',$phone)->count() !=0) return $this->returnJson(self::DATA_NOTFOUND,'手机号码或邮箱已存在' );
                if (User::where('username','=',$username)->count() !=0) return $this->returnJson(self::DATA_NOTFOUND,'用户名已存在' );
                if (!$grade_id = Grade::where('grade','=',$grade)->pluck('id')[0])return $this->returnJson(self::DATA_NOTFOUND,'年级错误' );
                if (!$role_id = Role::where('name','=',$role)->pluck('id')[0])return $this->returnJson(self::DATA_NOTFOUND,'职位错误' );

                $user_id= User::insertGetId([
                    'username'=>$username,
                    'email'=>$phone.'@bigdata.com',
                    'phone'=>$phone,
                    'grade_id'=>$grade_id,
                    'introduce'=>'暂无',
                    'password'=>md5('12345678'),
                    'create_time' => time(),
                    'is_first' => 1
                ]);

                UserRole::insert([
                    'user_id'=>$user_id,
                    'role_id' => $role_id
                ]);
            }
        }catch (\Exception $e){
            echo $e;
        }
    }

    public function createData($rows)
    {
        //todo
    }
}
